package http;

import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.GsonConverterFactory;
import retrofit2.Retrofit;

/**
 * Created by ZhangTAO on 2017/12/21.
 */

public class RetrofitUtils {
    private static volatile RetrofitUtils instance;
    private Retrofit retrofit;
    private Class service;

    //应用拦截器
    public class LoggingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request original = chain.request();
            HttpUrl url=original.url().newBuilder()
                    .addQueryParameter("source","android")
                    .build();
            //添加请求头
            Request request = original.newBuilder()
                    .url(url)
                    .build();
            return chain.proceed(request);
        }
    }
    public RetrofitUtils(String baseurl) {
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(new LoggingInterceptor())
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl(baseurl)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
    }
    public static RetrofitUtils getInstance(String baseurl) {
        if(instance == null) {
            synchronized (RetrofitUtils.class) {
                if(null == instance) {
                    instance = new RetrofitUtils(baseurl);
                }
            }
        }
            return instance;
    }
    public Retrofit getRetrofit() {
        return retrofit;
    }
    public void create(Class cls) {
        service = (Class) retrofit.create(cls);
    }
    public Class getService() {
        return service;
    }
}
